#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

#define _PORT_ 8888

void connect_server(int sock) {
    struct sockaddr_in client_addr;
    memset(&client_addr, 0, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(9999);
    client_addr.sin_addr.s_addr = htonl(0);

    int ret = connect(sock, (struct sockaddr*)&client_addr, sizeof(client_addr));
    if(ret < 0) {
        printf("连接失败\n");
        exit(1);
    }
    printf("tcp_client:连接TCP服务器成功\n");
    printf("tcp_client:服务器的文件描述符数: %d\n", sock);
}

int start(int sock) {
    if(sock < 0){
        printf("tcp_client: sock < 0");
        return -1;
    } 
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(_PORT_);  
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    int opt = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    if(bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        printf("tcp_client:绑定失败\n");
        return -1;
    }

    if(listen(sock, 5) < 0) {
        printf("tcp_client: listen失败\n");
        return -1;
    }
    return 0;
}

int main() 
{
    //连接TCP客户端
    int server_sock = socket(AF_INET, SOCK_STREAM, 0);
    connect_server(server_sock);

    //创建监听套接字连接NodeMCU
    //或者接收指令
    int my_sock = socket(AF_INET, SOCK_STREAM, 0);     
    int ret = start(my_sock);
    if(ret == -1) {
        printf("tcp_client:服务器启动失败\n");
    }
    printf("tcp_client:服务器启动成功\n");
    
    //一直监听有没有收到报文
    while(1) {
        //监听
        
        //拿到客户端的文件描述符， 读取第一行，判断是指令类型  还是NodeMCU的信息
        
        if() {
            //是NodeMUC发来的
            //将信息存到map中
            
        } else {
            //服务器发来的指令
            //再读一行，获取到名称，再从map中得到IP
            //向对应的IP发送指令，指令就是剩下的报文内容
            
        }
    }
    return 0;
}
